package com.tianqu.tms.www.transfer.controller;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.WeChatMqApi;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn000432Bo;
import com.tianqu.tms.dto.BaseCarInfoDto;
import com.tianqu.tms.dto.MarketCarInfoDto;
import com.tianqu.tms.dto.TransferAcceptedInfoDto;
import com.tianqu.tms.dto.TransferTicketdInfoDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.entity.TransferPersonalCarInfo;
import com.tianqu.tms.entity.TransferProcessHistory;
import com.tianqu.tms.entity.TransferSettlementInfo;
import com.tianqu.tms.www.transfer.action.PTransactionsSearchResultAction;
import com.tianqu.tms.www.transfer.actionform.TransferRgActionForm;
import com.tianqu.tms.www.transfer.viewhelper.TransferRgInputViewHelper;

public class PTransactionsInputResultController extends TmsController {
	private Logger logger = Logger.getLogger(PTransactionsInputResultController.class);
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = getTxController();
		
		try {
			controller.begin();
			TmsUserProfile profile = uc.getUserProfile();
			//开始从form取值 往数据库set值
			TransferRgActionForm form = (TransferRgActionForm)uc.getInputForm();
			TransferRgInputViewHelper view =(TransferRgInputViewHelper)uc.getAttribute(TmsConstants.VIEWHELP);
			toViewHelper(form,view);
			
			TransferAcceptedInfoDto transferAcceptedInfoDto = TransferAcceptedInfo.getInstance().getAssessInfo001(form.getSerial());
			TransferAcceptedInfoDto dto = new TransferAcceptedInfoDto();
			dto.setSerial(form.getSerial());
			dto.setTransNo(form.getTransNo());
			dto.setTransMarket(form.getTransMarket());
			dto.setVendorCode(form.getVendorCode());
			dto.setModelCode(form.getModelCode());
			dto.setCarMarketIn(form.getCarMarketIn());
			dto.setCarType(form.getCarType());
			dto.setCarUse(form.getCarUse());
			dto.setRegisterCardNo(form.getRegisterCardNo());
			MarketCarInfoDto info = Car.getInstance().getCtiyInfo(form.getCarMarketIn());
			if(info!=null) {
				dto.setCarMarketInProv(Integer.parseInt(info.getPrivilId()));
				dto.setCarMarketInCity(Integer.parseInt(info.getCityId()));
			}
			dto.setPrice(Integer.parseInt(form.getPrice()));
			dto.setCheckUserid(Integer.parseInt(form.getCheckUserId()));
			dto.setCarOwner(StringUtil.formatCarName(form.getCarOwner()));
			dto.setOwnerPhone(form.getOwnerPhone());
			dto.setOwnerAddress(form.getOwnerAddress());
			//
			dto.setNewCardNo(form.getNewIdentification());
			dto.setCardNo(form.getIdentification());
			
			dto.setNewcarOwner(StringUtil.formatCarName(form.getNewCarOwner()));
			dto.setNewOwnerPhone(form.getNewOwnerPhone());
			dto.setNewOwnerAddress(form.getNewOwnerAddress());
			dto.setChangeTradeTicket(Integer.parseInt(form.getChangeTradeTicket()));
			dto.setChangeBody(Integer.parseInt(form.getChangeBody()));
			TransferAcceptedInfo.getInstance().updateAcceptInfo001(dto);

			
			//--tms_transfer_process_history
			TransferProcessHistory history = new TransferProcessHistory();
			history.setSerial(form.getSerial());
			history.setInsertUserId(profile.getUniqueId());
			if("1".equals(form.getChangeTradeTicket())) history.setBusinessType(24);
			else history.setBusinessType(9);
			history.insertHisInfoAtAssess(history);
			
			//--
			BaseCarInfoDto baseCarInfoDto = new BaseCarInfoDto();
			baseCarInfoDto.setVin(form.getVin());
//			baseCarInfoDto.setCountryStyle(Integer.parseInt(form.getCountryStyle()));
			baseCarInfoDto.setCarUse(Integer.parseInt(form.getCarUse()));
			if (StringUtil.isNotBlank(form.getCarOwner())) {
				if (form.getCarOwner().length() > 5) baseCarInfoDto.setCardType(2);
				else baseCarInfoDto.setOwnerType(1);
			}
			baseCarInfoDto.setRegisterCardNo(form.getRegisterCardNo());
			baseCarInfoDto.setCarOwner(form.getCarOwner());
			baseCarInfoDto.setOwnerAddress(form.getOwnerAddress());
			baseCarInfoDto.setOwnerPhone(form.getOwnerPhone());
			baseCarInfoDto.setCarOwnerIdCardNo(form.getCarOwnerIdCardNo());
			baseCarInfoDto.setOwnerOrgNo(form.getOwnerOrgNo());
			baseCarInfoDto.setModelCode(form.getModelCode());
			baseCarInfoDto.setVendorCode(form.getVendorCode());
			baseCarInfoDto.setCarType(Integer.parseInt(form.getCarType()));
			Car.getInstance().updateBaseCarInfo(baseCarInfoDto);
			
			//--
			if(StringUtil.isNotBlank(form.getIdentification())) {
				MarketCarInfoDto marketCarInfoDto = new MarketCarInfoDto();
				marketCarInfoDto.setCarOwner(form.getCarOwner());
				marketCarInfoDto.setOwnerPhone(form.getOwnerPhone());
				marketCarInfoDto.setOwnerAddress(form.getOwnerAddress());
				marketCarInfoDto.setOwnerCardNo(form.getIdentification());
				if(StringUtil.isNotBlank(form.getCarOwner())) {
					if(form.getCarOwner().length() >=5) marketCarInfoDto.setOwnerType(2);
					else marketCarInfoDto.setOwnerType(1);
				}
				if(StringUtil.isNotBlank(form.getCardType())) marketCarInfoDto.setCardType(Integer.parseInt(form.getCardType()));
				List<MarketCarInfoDto> list = Car.getInstance().findCarOwnerByCardNo(form.getIdentification());
				if(list.size() == 0) Car.getInstance().insertCarOwner(marketCarInfoDto);
				else Car.getInstance().updateCarOwnerByOwnerCardNo(marketCarInfoDto);
			}
			
			if(StringUtil.isNotBlank(form.getNewIdentification())) {
				MarketCarInfoDto marketCarInfoDto = new MarketCarInfoDto();
				marketCarInfoDto.setCarOwner(form.getNewCarOwner());
				marketCarInfoDto.setOwnerPhone(form.getNewOwnerPhone());
				marketCarInfoDto.setOwnerAddress(form.getNewOwnerAddress());
				marketCarInfoDto.setOwnerCardNo(form.getNewIdentification());
				if(StringUtil.isNotBlank(form.getNewCarOwner())) {
					if(form.getNewCarOwner().length() >=5) marketCarInfoDto.setOwnerType(2);
					else marketCarInfoDto.setOwnerType(1);
				}
				if(StringUtil.isNotBlank(form.getCardType())) marketCarInfoDto.setCardType(Integer.parseInt(form.getCardType()));
				List<MarketCarInfoDto> list = Car.getInstance().findCarOwnerByCardNo(form.getNewIdentification());
				if(list.size() == 0) Car.getInstance().insertCarOwner(marketCarInfoDto);
				else Car.getInstance().updateCarOwnerByOwnerCardNo(marketCarInfoDto);
			}
			
			TransferSettlementInfo transferSettlementInfo = new TransferSettlementInfo();
			TransferTicketdInfoDto transferTicketdInfoDto = new TransferTicketdInfoDto();
			transferTicketdInfoDto.setSerial(form.getSerial());
			transferTicketdInfoDto.setLicensePlate(form.getLicensePlate());
			transferTicketdInfoDto.setVin(form.getVin());
			transferTicketdInfoDto.setModelCode(form.getModelCode());
			transferTicketdInfoDto.setVendorCode(form.getVendorCode());
			transferTicketdInfoDto.setCarType(form.getCarType());
			transferTicketdInfoDto.setCarUse(form.getCarUse());
			transferTicketdInfoDto.setRegisterCardNo(form.getRegisterCardNo());
			transferTicketdInfoDto.setCarMarketInName(form.getCarMarketIn());
			transferTicketdInfoDto.setMarketName(form.getMarketName());
			transferTicketdInfoDto.setTaxpayerNo(form.getTaxNo());
			transferTicketdInfoDto.setTransNo(form.getTransNo());
			transferTicketdInfoDto.setCarOwner(form.getCarOwner());
			transferTicketdInfoDto.setCarOwnerIdCardNo(form.getCarOwnerIdCardNo());
			transferTicketdInfoDto.setOwnerPhone(form.getOwnerPhone());
			transferTicketdInfoDto.setOwnerAddress(form.getOwnerAddress());
			transferTicketdInfoDto.setNewCarOwner(form.getNewCarOwner());
			transferTicketdInfoDto.setNewCarOwnerIdCardNo(form.getNewcarOwnerIdCardNo());
			transferTicketdInfoDto.setNewOwnerPhone(form.getNewOwnerPhone());
			transferTicketdInfoDto.setNewOwnerAddress(form.getNewOwnerAddress());
			transferTicketdInfoDto.setPrice(Integer.parseInt(form.getPrice()));
			transferTicketdInfoDto.setCheckUserid(form.getCheckUserId());
			transferTicketdInfoDto.setInsertUserid(profile.getUniqueId());	
			transferSettlementInfo.insertTransferTicketdInfo(transferTicketdInfoDto);
			
			PTransactionsSearchResultAction.toViewHelper(transferAcceptedInfoDto,view);
			
			//API 432
			TransferDataSyn000432Bo bo = new TransferDataSyn000432Bo();
			bo.setSerial(transferAcceptedInfoDto.getSerial());
			bo.setVendorCode(transferAcceptedInfoDto.getVendorCode());
			bo.setModelCode(transferAcceptedInfoDto.getModelCode());
			if(StringUtils.isNumeric(transferAcceptedInfoDto.getCarType())) bo.setCarType(Integer.parseInt(transferAcceptedInfoDto.getCarType()));
			if(StringUtils.isNumeric(transferAcceptedInfoDto.getCarUse())) bo.setCarUse(Integer.parseInt(transferAcceptedInfoDto.getCarUse()));
			bo.setRegisterCardNo(transferAcceptedInfoDto.getRegisterCardNo());
			bo.setCarMarketInCity(transferAcceptedInfoDto.getCarMarketInCity());
			bo.setCarMarketInProv(transferAcceptedInfoDto.getCarMarketInProv());
			bo.setPrice(transferAcceptedInfoDto.getPrice());
			bo.setOwnerType(transferAcceptedInfoDto.getOwnerType());
			bo.setOwnerOrgNo(transferAcceptedInfoDto.getOwnerOrgNo());
			bo.setCarOwnerIdCardNo(transferAcceptedInfoDto.getCarOwnerIdCardNo());
			bo.setCarOwner(transferAcceptedInfoDto.getCarOwner());
			bo.setOwnerPhone(transferAcceptedInfoDto.getOwnerPhone());
			bo.setOwnerAddress(transferAcceptedInfoDto.getOwnerAddress());
//			bo.setOwnerSex(ownerSex);
//			bo.setOwnerBirth(ownerBirth);
			bo.setNewOwnerType(transferAcceptedInfoDto.getNewOwnerType());
			bo.setNewOwnerOrgNo(transferAcceptedInfoDto.getNewOwnerOrgNo());
			bo.setNewCarOwnerIdCardNo(transferAcceptedInfoDto.getNewcarOwnerIdCardNo());
			bo.setNewCarOwner(transferAcceptedInfoDto.getNewcarOwner());
			bo.setNewOwnerPhone(transferAcceptedInfoDto.getNewOwnerPhone());
			bo.setNewOwnerAddress(transferAcceptedInfoDto.getNewOwnerAddress());
//			bo.setNewOwnerSex(newOwnerSex);
//			bo.setNewOwnerBirth(newOwnerBirth);
			bo.setMaketNo(TmsConstants.MARKET_NO);
			if(dto.getChangeTradeTicket() ==2 && dto.getChangeBody() ==1 ) bo.setStatus(12);
			else if(dto.getChangeTradeTicket() ==2 && dto.getChangeBody() ==2 ) bo.setStatus(10);
			else bo.setStatus(transferAcceptedInfoDto.getStatus());
			bo.setChangeTradeTicket(transferAcceptedInfoDto.getChangeTradeTicket());
			WeChatMqApi.getInstance().call(bo);
			//
			uc.setAttribute(TmsConstants.VIEWHELP, view);
			controller.commit();
		} catch (Exception e) {
			logger.error("PTransactionsInputResultController error,",e);
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}
		logger.debug(this.getClass().getName() + "#execute was completed.");
	}
	
	public static TransferRgInputViewHelper toViewHelper(TransferRgActionForm form,TransferRgInputViewHelper view) throws TmsDaoException {
		view.setCardType(form.getCardType());
		view.setCarType(form.getCarType());
		view.setCarUse(form.getCarUse());
		view.setCarMarketIn(form.getCarMarketIn());
		view.setCheckUserId(form.getCheckUserId());
		view.setOwnerType(form.getOwnerType());
		view.setOwnerType(form.getOwnerType());
		view.setChangeBody(form.getChangeBody());
		if(StringUtils.isNumeric(form.getChangeTradeTicket())) view.setChangeTradeTicket(Integer.parseInt(form.getChangeTradeTicket()));
		view.setSerial(form.getSerial());
		view.setVin(form.getVin());
		view.setLicensePlate(form.getLicensePlate());
		view.setRegisterCardNo(form.getRegisterCardNo());
		view.setTransNo(form.getTransNo());
		view.setPrice(form.getPrice());
		view.setIdentification(form.getIdentification());
		view.setCarOwner(form.getCarOwner());
		view.setOwnerPhone(form.getOwnerPhone());
		view.setOwnerAddress(form.getOwnerAddress());
		view.setNewIdentification(form.getNewIdentification());
		view.setNewCarOwner(form.getNewCarOwner());
		view.setNewOwnerPhone(form.getNewOwnerPhone());
		view.setNewOwnerAddress(form.getNewOwnerAddress());
		view.setVendorCode(form.getVendorCode());
		view.setModelCode(form.getModelCode());
		view.setRegisterCardNo(form.getRegisterCardNo());
		Codes code = Codes.getInstance();
		view.setCarUse(form.getCarUse());
		view.setCarMarketIn(form.getCarMarketIn());
		if(StringUtil.isNotBlank(form.getCarUse())) view.setCarUseName(code.getItemValueByItemIdAndItemCode(Codes.USER_NATURE,Integer.parseInt(form.getCarUse())));
		if(StringUtil.isNotBlank(form.getCarMarketIn())) {
			MarketCarInfoDto info = Car.getInstance().getCtiyInfo(form.getCarMarketIn());
			if(info!=null) view.setVaoName(info.getVaoName());
		} 
		return view;
	}
	
	public TransferRgInputViewHelper toViewHelper(TransferAcceptedInfoDto dto,TransferRgInputViewHelper view) throws TmsDaoException {
		if(dto.getOwnerType() == 1) view.setIdentification(dto.getCarOwnerIdCardNo());
		else view.setIdentification(dto.getOwnerOrgNo());
		
		if(dto.getNewOwnerType() == 1) view.setIdentification(dto.getNewcarOwnerIdCardNo());
		else view.setIdentification(dto.getNewOwnerOrgNo());
		
		view.setSerial(dto.getSerial());
		view.setLicensePlate(dto.getLicensePlate());
		view.setVin(dto.getVin());
		view.setCarType(dto.getCarType());
		view.setCarUse(dto.getCarUse());
		view.setRegisterCardNo(dto.getRegisterCardNo());
		view.setPrice(dto.getPrice() +"");
		view.setVendorCode(dto.getVendorCode());
		view.setModelCode(dto.getModelCode());
		view.setVaoName(dto.getVaoName());
		view.setRealName(dto.getRealName());
		view.setMarketName(dto.getMarketName());
		view.setOwnerType(dto.getOwnerType() +"");
		view.setCarOwnerIdCardNo(dto.getCarOwnerIdCardNo());
		view.setOwnerOrgNo(dto.getOwnerOrgNo());
		view.setCarOwner(dto.getCarOwner());
		view.setOwnerPhone(dto.getOwnerPhone());
		view.setOwnerAddress(dto.getOwnerAddress());
		view.setNewOwnerType(dto.getNewOwnerType() +"");
		view.setNewcarOwnerIdCardNo(dto.getNewcarOwnerIdCardNo());
		view.setNewOwnerOrgNo(dto.getNewOwnerOrgNo());
		view.setNewCarOwner(dto.getNewcarOwner());
		view.setNewOwnerPhone(dto.getNewOwnerPhone());
		view.setNewOwnerAddress(dto.getNewOwnerAddress());
		view.setChangeTradeTicket(dto.getChangeTradeTicket());
		view.setPg_printNum(dto.getPg_printNum() +"");
		view.setPg_printUserId(dto.getPg_printUserId() +"");
		view.setOther(dto.getOther() +"");
		view.setMonitoringSales(dto.getMonitoringSales() +"");
		return view;
	}
	
	/**
	 * 
	 * 将viewhelp中值set到entity中
	 * 
	 * @throws TmsDaoException
	 */
	private TransferPersonalCarInfo setEntityFromViewhelper1(TransferPersonalCarInfo entity, TransferRgInputViewHelper view)
			throws TmsDaoException {
		entity.setSerial(view.getBasicCarId());
		entity.setLicensePlate(view.getLicensePlate());
		entity.setVendorCode(view.getVendorCode());
		entity.setModelCode(view.getModelCode());
		if(view.getCarType()!=null && !"".equals(view.getCarType()))
		{
			entity.setCarType(Integer.parseInt(view.getCarType()));
		}else{
			entity.setCarType(0);
		}
		entity.setRegisterCardNo(view.getRegisterCardNo());
		if(view.getOwnerType()!=null && !"".equals(view.getOwnerType()))
		{
			entity.setOwnerType(Integer.parseInt(view.getOwnerType()));
		}else{
			entity.setOwnerType(0);
		}
		entity.setCarOwner(view.getCarOwner());
		entity.setCarOwnerIdCardNo(view.getCarOwnerIdCardNo());		
		entity.setOwnerOrgNo(view.getOwnerOrgNo());
		entity.setOwnerAddress(view.getOwnerAddress());
		entity.setOwnerPhone(view.getOwnerPhone());
		return entity;
	}
	
	public static int diffDays(Date fDate, Date oDate) {
	       Calendar aCalendar = Calendar.getInstance();
	       aCalendar.setTime(fDate);
	       int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
	       aCalendar.setTime(oDate);
	       int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
	       return day2 - day1;
	    }
	
	private boolean getDistanceTimes(String str1, String str2){  
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");    
        long day = 0;
        Date one = null;
        Date two = null;
        boolean result = false;
        try{
        	if(!StringUtil.isNullOrBlank(str1)&&!StringUtil.isNullOrBlank(str2)){
	        	one = df.parse(str1);  
	        	two = df.parse(str2);  
		        long time1 = one.getTime();  
		        long time2 = two.getTime();  
		        long diff = 0 ;  
		        if(time1<time2) {  
		            diff = time2 - time1;
		            day = diff / (24 * 60 * 60 * 1000);  
		            if(day != 1){
		            	result = true;
		            }
		        } else {  
		        	result = true;  
		        }
        	}else{
        		result = true;
        	}
		} catch (ParseException e) {  
	        e.printStackTrace();  
	    }  
        return result;  
    }
}
